<template>
  <a-modal
    :title="title"
    :style="{ top: '10px' }"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <template slot="footer">
      <a-button type="primary" :disabled="status =='2' || status =='1'" @click="handleOk">保存</a-button>
      <a-button type="danger" :disabled="status =='2' || status =='1'" @click="handleSubmit">提交</a-button>
      <a-button @click="handleCancel">关闭</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-tabs :activeKey="activeKey" @change="callback">
        <a-tab-pane key="1">
          <span slot="tab">
            <a-icon type="edit" />
            基本信息
          </span>
          <a-form :form="form">
            <template v-for="s in formData" >
              <a-form-item
                v-if="s.nType == '1'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
                <a-input v-decorator="[ `${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" />
              </a-form-item>
		                
              <a-form-item
                v-if="s.nType == '4'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
                <mySelect
                  :ref="s.code"
                  @change="handleSelectChange"
                  v-decorator="[`${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]"
                  :settings="{url:'cutDictionaryDetail/getAll',params:{parentId : `${s.dictionary}`}, showSearch : true, allowClear : true,id:`${s.code}`}"/>           
              </a-form-item>
              <a-form-item
                v-show="false" 
                v-if="s.nType == '4'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
		             
                <a-input v-decorator="[ 't'+`${s.code}`]" />
		         
              </a-form-item>
              <a-form-item
                v-if="s.nType == '3'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
                <a-date-picker 
                  v-decorator="[`${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]"
                />          
              </a-form-item>
              <a-form-item
                v-if="s.nType == '2'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
                <a-input-number :min="0" v-decorator="[ `${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]" />
              </a-form-item>
            
              <a-form-item
                v-if="s.nType == '7'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
                <mySelect
                  :ref="s.code"
                  @change="handleSelectChange"
                  v-decorator="[`${s.code}`, {rules: [{required: `${s.is_required}` == 'true'? true : false, message: `${s.name}` + '不能为空！'}]}]"
                  :settings="{url:'cutContent/getBySettingId',params:{settingId : `${s.dictionary}`}, showSearch : true, allowClear : true,id:`${s.code}`}"/>           
              </a-form-item>
              <a-form-item
                v-show="false" 
                v-if="s.nType == '7'"
                :label="s.name"
                :labelCol="{span: 4}"
                :wrapperCol="{span: 19}"
              >
                    
                <a-input v-decorator="[ 't'+`${s.code}`]" />
                
              </a-form-item>
            </template>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2" v-if="hasPerson">
          <span slot="tab">
            <a-icon type="team" />成员信息
          </span>
          <a-table
            class="components-table-demo-nested"
            ref="table" 
            :columns="columns" 
            :row-key="record => record.id" 
            :data-source="data" 
            :pagination="false">
            <span slot="action" slot-scope="text, record">
              <template>
                <a-popconfirm
                  title="是否删除该条记录?"
                  @confirm="confirm(record)"
                  @cancel="cancel"
                  okText="是"
                  cancelText="否"
                >
                  <a href="#">删除</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a @click="handleEdit(record)">编辑</a>
              </template>
            </span>
            <span slot="status" slot-scope="text, record">
              <template>
                <a-tag :color="record.statusId==='0'?'#f50':'#87d068'" >
                  {{ text }}
                </a-tag>
              </template>
            </span>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="4">
          <span slot="tab">
            <a-icon type="form" />审核意见
          </span>
          <a-textarea
            readOnly
            style="margin-top: 10px;"
            v-model="opinion" 
            placeholder="请输入审核意见,不超过500字"
            :rows="4"
            maxLength="500"/>
        </a-tab-pane>
        <div class="editable-add-btn" v-show="this.activeKey == '2' && (this.status == '0' || this.status == '3')" slot="tabBarExtraContent">          <a-button-group>
          <a-button type="primary" @click="handleAddPerson('0')"> <a-icon type="plus" />添加校内人员 </a-button>
          <a-button @click="handleAddPerson('1')"> 添加其他人员<a-icon type="plus"/> </a-button>
        </a-button-group>
        </div>
      </a-tabs>
    </a-spin>
    <performance-person-add-modal ref="modal" @ok="handleddOk"></performance-person-add-modal>
  </a-modal>
</template>


<script>
import pick from 'lodash.pick'
  import {
    postAxiosUrl,
    getUrl
  } from '@/api/manage'
  import mySelect from '../../myComponent/MySelect'
  import moment from 'moment'
  import PerformancePersonAddModal from './PerformancePersonAddModal'
  
export default {
  components:{
    mySelect,
    PerformancePersonAddModal
  },
  data () {
    return {
      id : '',
      status : '',
      opinion : '',
      settingId: '',
      checked : false,
      visible: false,
      confirmLoading: false,
      formData : [],
      form: this.$form.createForm(this),
      title : '',
      activeKey : '1',
      hasPerson : false,
      hasPaper : false,
      columns: [],
      data: [],
    }
  },
  created () {
    
  },
  methods: {
  add (settingId, activeName) {
    this.title=activeName
    this.activeKey = '1'
    this.status = '0'
    this.id = 'new'+this.getUUID()
    this.visible = true
    this.settingId = settingId
    this.formData = []
    this.hasPerson = false
     this.hasPaper = false
    if(activeName == '教学论文'|| activeName == '科研论文'){
      this.hasPaper = true
    }
    this.fetch()
  },
  edit (record, settingId, activeName) {
    this.title=activeName
    this.id = record.id
    this.settingId = settingId
    this.activeKey = '1'
    this.visible = true
    this.formData = []
    this.hasPerson = false
    this.hasPaper = false
    this.fetch(record)
  },
  callback(key){
    this.activeKey = key
    if(this.activeKey == '2'){
      this.getData(this.id)
    }else if(this.activeKey == '3'){
      this.$nextTick(() => {
        this.$refs.paper.init(this.id)
      })
      
    }
  },
  fetch(record) {
    this.loading = true
    var _this = this
    return getUrl('cutSedSettingDetail/getDetail', {settingId : this.settingId})
      .then(data => {
        _this.formData = data.result.data
        _this.hasPerson = data.result.hasPerson
        if(record){
          _this.fetchContent(record)
        }
      })
  },
  getData(parentId) {
      var _this = this
       _this.myLoading = true
      getUrl('cutContentPerson/getAll', {contentId : parentId, settingId : this.settingId})
        .then(res => {
           _this.myLoading = false
          _this.data = res.result.data
          _this.columns = res.result.columns
          
         if(_this.columns != ''){
           _this.columns.push({
                title: '操作',
                width : 150,
                fixed: 'right',
                scopedSlots: { customRender: 'action' }
              })
         }
        })
    
  },
  fetchContent(record) {
    this.confirmLoading = true
    var _this = this
    return getUrl('cutContent/getById', {id : this.id})
      .then(data => {
         _this.confirmLoading = false
        
          const { form: { setFieldsValue } } = _this
  
            _this.$nextTick(() => {debugger
              var red = JSON.parse(data.result.cutContent.data)
              _this.status = data.result.cutContent.status
              _this.opinion = data.result.cutContent.opinion
              _this.formData.forEach((item, index) => {
                 if(item.n_type == '4' || item.n_type == '7'){
                    setFieldsValue(pick(red, [item.code]))
                    setFieldsValue(pick(red, ['t'+item.code]))
                    _this.$refs[item.code][0].selectModel = red[item.code]
                 }else if(item.n_type == '3'){
                   if(red[item.code] != ''){
                     setFieldsValue({
                       [item.code] : moment(red[item.code], 'YYYY-MM-DD'),
                     })
                   }
                 }else{
                   setFieldsValue(pick(red, [item.code]))
                 }
              })
          })
      })
  },
  handleSelectChange(v1, v2, id){
      var text = v2.componentOptions.children[0].text
      this.form.setFieldsValue({
        ['t'+id] : text,
      })
  },
  close () {
      this.$emit('close')
      this.visible = false
  },
  handleCancel () {
      this.close()
  },
  processData(values){
    var data = []
    var jsonStr = ''
    var jsonData = {}
    this.formData.forEach((item, index) => {
      if(item.n_type == '4' || item.n_type == '7'){
        jsonData[item.code] = values[item.code]
         jsonData['t'+item.code] = values['t'+item.code]
      }else if(item.n_type == '3'){
        var value = values[item.code]
        if(value != null && value != '' && value != undefined){
          value = value.format('YYYY-MM-DD')
        }else{
           value = ''
        }
        jsonData[item.code] =value
      }else if(item.n_type == '2'){
        jsonData[item.code] = values[item.code] ==null ? '' : values[item.code]
      }else{
        jsonData[item.code] = values[item.code]
      }
    })
    return JSON.stringify(jsonData )
  },
  handleOk () {
     var _this = this
      _this.confirmLoading = true
      const values =  this.form.getFieldsValue()
      values.id = this.id
      values.settingId = this.settingId
      values.data = _this.processData(values)
      postAxiosUrl('cutContent/save', values)
        .then(data => {
           if(!data.success){
              _this.$message.warning(data.error)
              _this.confirmLoading = false
            }else{
              _this.visible = false
              _this.confirmLoading = false
              _this.$emit('ok', values)
            }           
          })
     
    },
    handleSubmit () {
        if(this.activeKey == '3'){
          var personInfo = this.$refs.paper.submitForm(this.id)
          if(personInfo != 'error'){
            this.validateForm()
          }
         
        }else{
          // 触发表单验证
          this.validateForm()
        }
      },
    validateForm(){
       const _this = this
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log('form values', values)
          _this.confirmLoading = true
         values.id = this.id
         values.settingId = this.settingId
         values.data = _this.processData(values)
         postAxiosUrl('cutContent/submit', values)
           .then(data => {
              if(!data.success){
                 _this.$message.warning(data.error)
                 _this.confirmLoading = false
               }else{
                 _this.visible = false
                 _this.confirmLoading = false
                 _this.$emit('ok', values)
               }           
             })
        }else{
          this.activeKey = '1'
        }
      })
    },
    handleAddPerson(type){
      this.$refs.modal.add(this.settingId, this.id, type)
    },
    handleddOk(){
      this.getData(this.id)
    },
    confirm (record) {
      const me = this
            postAxiosUrl('cutContentPerson/del', {id : record.id})
              .then(res => {
                me.getData(me.id)
              })
    },
    handleEdit (record) {
        this.$refs.modal.edit(record, this.settingId, this.id)
    },
    cancel() {
      
    }
  }
}
</script>

<style>
  .ant-btn-danger{
        color: #ffffff;
        background-color: #f5222d;
  }
  .ant-btn-danger:focus {
      color: #ffffff;
      background-color: #f5222d;
      }
</style>
